<template>
<ContentFiled v-if="!$store.state.user.pulling_info">
    <div class="row justify-content-md-center">
        <div class="col-3">
            <form @submit.prevent= "login">
                <div class="mb-3">
                    <label class="form-label">用户名</label>
                    <input v-model="username" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="请输入用户名">
                </div>
                <div class="mb-3">
                    <label class="form-label">密码</label>
                    <input v-model="password" type="password" class="form-control" id="exampleInputPassword1" placeholder="请输入密码">
                </div>
                <div class="error_message">{{error_message}}</div>
                <button type="submit" class="btn btn-primary">登录</button>
            </form>
        </div>
    </div>
</ContentFiled>
</template>

<script>
import ContentFiled from "@/components/ContentFiled.vue"
import {useStore} from "vuex"
import {ref} from "vue"
import router from "@/router/index"

export default {
    components:{
        ContentFiled
    },
    setup(){
        let username = ref(""); //凡是ref都得 .value
        let password = ref("");
        let error_message = ref("");
        const store = useStore();

        const jwt_token = localStorage.getItem("jwt_token");
        if(jwt_token){ //如果本地有token
            store.commit("updateToken",jwt_token);
            store.dispatch("getinfo",{
                success(){
                    //这里是成功之后调用的回调函数
                    router.push({name:"home"});
                    store.commit("updatePullingInfo",false);
                },
                error(){ //以后是jwt-token 过期的一个失败
                    error_message.value = "出错了，请重试";
                    store.commit("updatePullingInfo",false);
                }
            })
        }else{
            store.commit("updatePullingInfo",false);
        }
        const login = () =>{
            error_message.value ="";
            store.dispatch("login",{
                username:username.value,
                password:password.value,
                success(){
                    store.dispatch("getinfo",{
                        success(){
                            //这里是成功之后调用的回调函数
                            router.push({name:"home"});
                        },
                        error(){
                            error_message.value = "出错了，请重试";
                        }
                    });
                },
                error(){
                    error_message.value = "用户名或密码错误";            
                }
            })
        }
        return {
            username,
            password,
            login,
            error_message,
        }
    }
}
</script>

<style scoped>
button{
    width: 100%;
}
div.error_message{
    color: red;
}
</style>